import React, { Component } from "react";
import { connect } from "dva";
import { Input, Form, Row, Col, Button, Select } from "antd";
import ChainInputBox from "./ChainInputBox";
import SceneDataChainInputBox from "./SceneDataChainInput";
import styles from "./PushAppAdd.less";

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

function SubTitle(props) {
  return (
    <Col span={24} className={styles.subTitle}>
      <b>{props.title}</b>
    </Col>
  );
}

@connect(stores => ({
  pushAppData: stores.pushApp,
  sceneTypeList: stores.pushScene.sceneTypeList
}))
@Form.create({
  mapPropsToFields(props) {
    const {
      pushAppData: { pushAppDetail: { opTypes = [], sceneDate = [] } = {} } = {}
    } = props;
    return {
      opTypes: Form.createFormField({ value: opTypes }),
      sceneDate: Form.createFormField({ value: sceneDate })
    };
  }
})
class PushAppAdd extends Component {
  componentDidMount() {
    this.init();
  }

  init = () => {
    const { dispatch } = this.props;
    dispatch({ type: "pushApp/getAppType" });
  };

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: "pushApp/setState", payload: { pushAppDetail: {} } });
  }

  // 提交
  handleOk = () => {
    const {
      dataSource,
      form: { validateFields },
      dispatch
    } = this.props;
    validateFields((err, values = {}) => {
      if (err) {
        return;
      }
      const temp = {
        ...values,
        opTypes: (values.opTypes || []).filter(
          item => JSON.stringify(item) !== JSON.stringify({})
        ),
        sceneDate: (values.sceneDate || []).filter(
          item => JSON.stringify(item) !== JSON.stringify({})
        )
      };
      if (dataSource && dataSource.appId) {
        const params = {
          ...temp,
          appId: dataSource.appId,
          creator: undefined
        };
        dispatch({
          type: "pushApp/pushAppConfigSave",
          payload: params
        });
      } else {
        dispatch({
          type: "pushApp/pushAppConfigSave",
          payload: temp
        });
      }
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      dataSource: { appId, appName, appType, appDesc } = {},
      pushAppData: {
        appTypeList = [],
        pushAppDetail: { opTypes = [], sceneDate = [], topic } = {}
      },
      sceneTypeList = [],
      closeModal
    } = this.props;
    return (
      <div className={styles.root}>
        <div className={styles.title}>{appId ? "编辑应用" : "新增应用"}</div>
        <Form layout="inline">
          <Row>
            <Col span={24}>
              <span style={{ color: "#f5222d" }}>{`* `}</span>
              <span>
                接入应用前请了解应用接入说明:<a>《应用接入说明》</a>
              </span>
            </Col>
            <SubTitle title={"基础信息"} />
            <Col md={24} lg={14}>
              <FormItem
                label={"应用名称"}
                className={`${styles.selectTitle} ${styles.twoItem}`}
              >
                {getFieldDecorator("appName", {
                  rules: [
                    {
                      required: true,
                      message: "请输入应用名称!"
                    },
                    {
                      pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
                      message: "应用名称含非法字符!"
                    }
                  ],
                  initialValue: appName
                })(<Input maxLength={30} />)}
              </FormItem>
            </Col>
            <Col md={24} lg={10}>
              <FormItem
                label={"应用类型"}
                className={`${styles.selectTitle} ${styles.twoItem}`}
              >
                {getFieldDecorator("appType", {
                  rules: [
                    {
                      required: true,
                      message: "请选择应用类型!"
                    }
                  ],
                  initialValue: appType
                })(
                  <Select>
                    {appTypeList.map(
                      ({ appType: appTypeLabel, id: appTypeId }) => (
                        <Option value={appTypeId} key={appTypeId}>
                          {appTypeLabel}
                        </Option>
                      )
                    )}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={24}>
              <FormItem
                label={"接入说明"}
                className={`${styles.selectTitle} ${styles.oneItem}`}
              >
                {getFieldDecorator("appDesc", {
                  rules: [
                    {
                      required: true,
                      message: "请输入接入说明!"
                    }
                  ],
                  initialValue: appDesc
                })(
                  <TextArea
                    placeholder="请输入接入说明,300字以内"
                    rows={4}
                    maxLength={300}
                  />
                )}
              </FormItem>
            </Col>
            <Col span={24}>
              <FormItem
                label={"日志采集topic"}
                className={`${styles.selectTitle} ${styles.oneItem}`}
              >
                {getFieldDecorator("topic", {
                  rules: [
                    {
                      required: true,
                      message: "请输入日志采集topic!"
                    }
                  ],
                  initialValue: topic
                })(<Input maxLength={30} style={{ width: "65%" }} />)}
              </FormItem>
            </Col>
            <SubTitle title={"推送触发动作"} />
            <Col span={24}>
              <FormItem
                label={"推送动作"}
                className={`${styles.selectTitle} ${styles.oneItem}`}
              >
                {getFieldDecorator("opTypes", {
                  initialValue: opTypes,
                  validateTrigger: false,
                  rules: [
                    {
                      validator: (rule, value = [], callback) => {
                        value.forEach(
                          (
                            { opTypeName, opFieldName, opTypeCode },
                            index,
                            array
                          ) => {
                            if (index === 0 && array.length === 1) {
                              if (!opTypeName && !opFieldName && !opTypeCode) {
                                callback();
                              }
                            }
                            if (!opTypeName || !opFieldName || !opTypeCode) {
                              callback("请输入完整的动作名称-字段名-值");
                            }
                          }
                        );
                        callback();
                      }
                    }
                  ]
                })(
                  <ChainInputBox
                    field={{
                      opTypeName: (
                        <Input
                          maxLength={30}
                          placeholder={"动作名称"}
                          style={{ width: "150px" }}
                        />
                      ),
                      opFieldName: (
                        <Input
                          maxLength={30}
                          placeholder={"字段名"}
                          style={{ width: "150px" }}
                        />
                      ),
                      opTypeCode: (
                        <Input
                          maxLength={30}
                          placeholder={"值"}
                          style={{ width: "150px" }}
                        />
                      )
                    }}
                  />
                )}
              </FormItem>
            </Col>
            <SubTitle title={"场景数据源"} />
            <Col span={24}>
              <FormItem
                label={"场景输入"}
                className={`${styles.selectTitle} ${styles.oneItem}`}
              >
                {getFieldDecorator("sceneDate", {
                  initialValue: sceneDate,
                  validateTrigger: false,
                  rules: [
                    {
                      validator: (rule, value = [], callback) => {
                        value.forEach(
                          (
                            {
                              dataSource,
                              sceneType,
                              logdataField,
                              fieldCode,
                              tableCode,
                              tableProject
                            },
                            index,
                            array
                          ) => {
                            if (index === 0 && array.length === 1) {
                              if (
                                !dataSource &&
                                !sceneType &&
                                !logdataField &&
                                !fieldCode
                              ) {
                                callback();
                              }
                            }
                            if (
                              dataSource === "F2" &&
                              (!sceneType || !tableProject || !tableCode)
                            ) {
                              callback(
                                "请输入完整的数据接入方式-场景类型-projectName-topicName"
                              );
                            }
                            if (
                              dataSource !== "F2" &&
                              (!sceneType || !logdataField || !fieldCode)
                            ) {
                              callback("请输入完整的场景类型-数据来源-字段名");
                            }
                          }
                        );
                        callback();
                      }
                    }
                  ]
                })(<SceneDataChainInputBox max={sceneTypeList.length} />)}
              </FormItem>
            </Col>
          </Row>
        </Form>
        <div className={styles.btnGroup}>
          <Button onClick={closeModal}>取消</Button>
          <Button type="primary" onClick={this.handleOk}>
            保存
          </Button>
        </div>
      </div>
    );
  }
}

export default PushAppAdd;
